<?php

/**
 * Created by PhpStorm.
 * User: ronghao
 * Date: 17/6/24
 * Time: 下午2:56
 */
class WxActivitiesBotComponent extends Component
{
    var $server_host = 'www.135plat.com';
    public static $SINA_APP_KEY = '203379639';

    private $splitStr = "\n";

    public function sendActivityMsgByOwner($activityId, $groupIds)
    {
        if (empty($groupIds) || empty($activityId))
            return;

        $activity = $this->getRelatedData('WxActivity',$activityId);

        $this->sendActivityMsgToGroups($activity, $groupIds);
    }

    public function sendDeliverMsgByOrder($orderId) {

        $order = $this->getOrderById($orderId);

        $status = $order['Order']['status'];
        $source = $order['Order']['source'];

        if ( $status != 2 || !$this->startsWith($source, 'group_') ){
            return; //非发货订单，非群内消息
        }
        $group_id = str_replace('group_','',$source);
        $msgcontent= '@'.$order['Order']['nickname'].' 您预订的'.$order['Order']['name'];
        foreach($order['Cart'] as $cart) {
            $msgcontent.= $cart['name'].'x'.$cart['num'].',';
        }

        if($order['Order']['ship_type'] == 200){
            $msgcontent .= '已经到达自提点了，注意去取哦。';
        }
        else{
            $msgcontent .= '发出快递了。';
            $ship_type = array(
                101=>'申通',
                102=>'圆通',
                103=>'韵达',
                104=>'顺丰',
                105=>'EMS',
                106=>'邮政包裹',
                107=>'天天',
                108=>'汇通',
                109=>'中通',
                //200=>'自提',
            );
            if($order['Order']['ship_type']){
                $msgcontent .= '快递类型:'.$ship_type[$order['Order']['ship_type']].'，';
            }
            if($order['Order']['ship_code']){
                $msgcontent .= '快递单号：'.$order['Order']['ship_code'].'。';
            }
            $msgcontent .= '请注意查收。';

        }
        $this->sendGroupMsg($group_id,$msgcontent);
    }

    public function sendActivityMsgByOrder($orderId)
    {
        if (empty($orderId))
            return;

        $order = $this->getOrderById($orderId);

        $model = $order['Order']['model'];
        $status = $order['Order']['status'];

        if ( $status != 1 )
            return;

        $source = $order['Order']['source'];
        $data_id = $order['Order']['data_id'];

        if ( $model && $data_id ) {
            $model_data = $this->getRelatedData($model,$data_id);
        }
        else{
            $model_data = array();
        }

        $groupId = 0;
        if ( $model == 'WxActivity' && !empty($source) && $this->startsWith($source, 'group_')) {
            $groupId = str_replace("group_", "", $source);
            $this->sendActivityMsgToGroups($model_data, array($groupId));
        }

        $this->sendOrderMsgToOwner($order, $model_data,$groupId);
    }

    public function sendGroupMsgByAid($activity, $groupIds, $msgtpl)
    {
        $activityId = $activity['WxActivity']['id'];
        $bot_model = loadModelObject('BotGroup');
        $groups = $bot_model->find('all', array(
            'conditions' => array(
                'BotGroup.id' => $groupIds,
            ),
            'recursive' => 1,
            'fields' => array('BotGroup.*', 'Bot.*'),
        ));

        $coverImg = $activity['WxActivity']['coverimg'];
        if($coverImg) {
            App::uses('CrawlUtility','Utility');
            $coverFile = UPLOAD_FILE_PATH . CrawlUtility::saveImagesByUrl($coverImg,null,array('oss'=>false));
        }

        foreach ($groups as $g) {
            $url = 'http://' . $g['Bot']['serverip'] . ':' . $g['Bot']['port'];
            if (strpos($msgtpl, '{groupid}') !== false) {
                $msgcontent = str_replace('{groupid}', $g['BotGroup']['id'], $msgtpl);
            } else {
                $msgcontent = $msgtpl;
            }

            $buyUrl = "http://{$this->server_host}/wx_activities/view/{$activityId}?source=group_" . $g['BotGroup']['id'];

            $msgcontent .= $this->sinaShortenUrl($buyUrl);

//            if($coverImg) { //发送封面图片消息
//                $this->sendMessage("groups", $g['BotGroup']['name'], $coverFile, $url,'image');
//            }

            //$this->sendMessage("groups", $g['BotGroup']['name'], $msgcontent, $url);
            $this->sendBotMessage("groups", $g['BotGroup']['name'], $msgcontent, $g['Bot']['id']);
        }
        if($coverImg) {
            unlink($coverFile);
        }
    }

    private function sendActivityMsgToGroups($activity, $groupIds)
    {
        $activityMsg = $this->getActivityInfo($activity);
        $this->sendGroupMsgByAid($activity, $groupIds, $activityMsg);
    }

    public function sendGroupMsg($groupIds,$msgcontent){
        $group_model = loadModelObject('BotGroup');

        $groups = $group_model->find('all', array(
            'conditions' => array(
                'BotGroup.id' => $groupIds,
            ),
            'recursive' => 1,
            'fields' => array('BotGroup.*', 'Bot.*'),
        ));
        foreach ($groups as $g) {
//            $url = 'http://' . $g['Bot']['serverip'] . ':' . $g['Bot']['port'];
//            $this->sendMessage("groups", $g['BotGroup']['name'], $msgcontent, $url);
            $this->sendBotMessage("groups", $g['BotGroup']['name'], $msgcontent, $g['Bot']['id']);
        }
    }

    public function sendFriendMsg($bot_id, $username,$msgcontent) {

        $bot_model = loadModelObject('Bot');
        $bot = $bot_model->find('first', array(
            'conditions' => array(
                'Bot.id' => $bot_id,
            ),
            'fields' => 'Bot.*',
            'recursive' => -1,
        ));

//        $url = 'http://' . $bot['Bot']['serverip'] . ':' . $bot['Bot']['port'];
//        $this->sendMessage("friends", $username, $msgcontent, $url);
        $this->sendBotMessage("friends", $username, $msgcontent, $bot['Bot']['id']);
    }

    private function sendOrderMsgToOwner($order, $model_data,$groupId)
    {
        $orderPaidMsg = $this->getOrderInfo($order, $model_data);
        $model = $order['Order']['model'] ;

        if($groupId) { //订单来源于群时，使用群对应的机器人，通知群主。
            $group_model = loadModelObject('BotGroup');
            $group = $group_model->find('first', array(
                'conditions' => array(
                    'BotGroup.id' => $groupId,
                ),
                'recursive' => 1,
                'fields' => array('BotGroup.*', 'Bot.*'),
            ));
            $username = $group['BotGroup']['username'];
            if (!empty($group)) {
//                $url = 'http://' . $group['Bot']['serverip'] . ':' . $group['Bot']['port'];
//                $this->sendMessage("friends", $username, $orderPaidMsg, $url);
                $this->sendBotMessage("friends", $username, $orderPaidMsg, $group['Bot']['id']);
            }
            if( $model_data[$model]['creator'] == $group['BotGroup']['creator'] ) {
                return; // 群主是活动发起人时，已经给群主发过了，直接返回。
            }
        }

        { // 订单没有群时，或者有群但不是群主发出的活动，使用第一个关联的机器人像活动发起人发送消息。
            $bot_model = loadModelObject('Bot');
            $group = $bot_model->find('first', array(
                'joins' => array(
                    array(
                        'table' => 'bot_group_members',
                        'alias' => 'BotGroupMember',
                        'type' => 'inner',
                        'conditions' => array(
                            'BotGroupMember.bot_id=Bot.id',
                            'BotGroupMember.user_id' => $model_data[$model]['creator'],
                        ),
                    )
                ),
                'fields' => array('BotGroupMember.nickname', 'Bot.*'),
                'recursive' => 1,
            ));
            $username = $group['BotGroupMember']['nickname'];
            if ( !empty($group) ) {
                //$url = 'http://' . $group['Bot']['serverip'] . ':' . $group['Bot']['port'];
                //$this->sendMessage("friends", $username, $orderPaidMsg, $url);
                $this->sendBotMessage("friends", $username, $orderPaidMsg, $group['Bot']['id']);
            }
        }
    }

    public function getOrderInfo($order, $model_data)
    {
        $model = $order['Order']['model'];
        $data_id = $order['Order']['data_id'];
        $order_id = $order['Order']['id'];

        $user_model = loadModelObject('User');
        $user = $user_model->find('first', array(
            'conditions' => array(
                'User.id' => $order['Order']['creator']
            ),
            'fields' => array('username'),
            'recursive' => -1,
        ));
        $userName = $user['User']['username'];

        $carts = $order['Cart'];

        $cartsMsg = "";
        //一个订单对应多条cart
        if(is_array($carts)) {
            foreach ($carts as $cart) {
                $cartName = $cart['name'];
                $cartNum = $cart['num'];
                $cartsMsg .= $cartName . "  " . $cartNum . "份  ".($cartNum*$cart['price'])."元\n";
            }
        }
        if ($order['Order']['total_price'] != 0){
            $cartsMsg .= "总金额：" . $order['Order']['total_price'];
        }

        if( $model_data ) {
            $relateName = $model_data[$model]['name'];
            $userMsg = '🎏 '.$userName . "预定" . $relateName . "成功";
        }
        else{
            $userMsg = '🎏 收到用户“'.$userName . '”新下订单';
        }

        $consigneeName = $order['Order']['consignee_name'];
        $consigneeMobilephone = $order['Order']['consignee_mobilephone'];
        $consigneeAddress = $order['Order']['consignee_province'] . $order['Order']['consignee_city'] . $order['Order']['consignee_area'] . $order['Order']['consignee_address'];
        $consigneeMsg = "姓名：" . $consigneeName . "\n"
            . "手机：" . $consigneeMobilephone . "\n"
            . "地址：" . $consigneeAddress;

        $orderUrl = "http://{$this->server_host}/orders/mine?type=shop&id={$order_id}&model={$model}&data_id={$data_id}";
        $orderPaidMsg = $userMsg . "\n" . $this->splitStr . $cartsMsg . "\n" . $this->splitStr . $consigneeMsg . "\n" . $this->splitStr
            . "🕹查看订单详情：" . $this->sinaShortenUrl($orderUrl);

        return $orderPaidMsg;

    }

    private function getActivityInfo($activity)
    {
        $activityId = $activity['WxActivity']['id'];

        $message = $activity['WxActivity']['name'] . "\n"
            . usubstr($activity['WxActivity']['summary'],0,200,'...' ). "\n";


        $itemsMsg = "";

        if ($activity['WxActivity']['model'] == 'Baoming') {
            $itemsMsg = $this->getBaomingsAndOrdersInfo($activityId);
        }
        if( !empty($itemsMsg) ){
            $message .= $itemsMsg;
            if( strpos($itemsMsg,'抢沙发') === false ){
                $message .= $this->splitStr."🔍参与戳这里👇：\n";
            }
        }
        return $message;
    }

    private function getBaomingsAndOrdersInfo($activityId)
    {
        $itemsMsg = "";
        $baoming = loadModelObject('Baoming');
        $baomings = $baoming->find('all', array(
            'conditions' => array(
                'Baoming.data_id' => $activityId
            ),
            'order' => 'Baoming.id ASC',
        ));

        if (empty($baomings))
            return $itemsMsg;

        $num_pres = array('1⃣','2⃣','3⃣','4⃣','5⃣','6⃣','7⃣','8⃣','9⃣','🔟',
            '⑾','⑿','⒀','⒁','⒂','⒃','⒄','⒅','⒆','⒇');

        $startNum = 0;//65;//A、B、C、D、E、F
        $itemArrayNos = array();
        foreach ($baomings as $item) {
            $itemKeyName = $num_pres[$startNum];//strtoupper(chr($startNum));
            $itemName = $item['Baoming']['name'];
            $itemArrayNos[$itemName] = $itemKeyName;
            $startNum++;
        }

        $userOrdersMsgAndSaledNums = $this->getUserOrdersInfo($activityId, $itemArrayNos);
        $userOrdersMsg = $userOrdersMsgAndSaledNums[0];
        $saledNums = $userOrdersMsgAndSaledNums[1];

        foreach ($baomings as $item) {
            $itemId = $item['Baoming']['id'];
            $itemName = $item['Baoming']['name'];

//            $itemStorage = $item['Baoming']['storage'];
//            $itemSaled = empty($saledNums[$itemId]) ? 0 : $saledNums[$itemId];
            $itemPrice = $item['Baoming']['price'];

            $itemsMsg = $itemsMsg . $itemArrayNos[$itemName] . " " . $itemName;
//            if ($itemStorage > 0) {
//                $itemsMsg = $itemsMsg . "(" . $itemStorage;
//                if ($itemSaled > 0) {
//                    $itemsMsg = $itemsMsg . "，已报名" . $itemSaled . ")";
//                } else {
//                    $itemsMsg = $itemsMsg . ")";
//                }
//            } else {
//                if ($itemSaled > 0) {
//                    $itemsMsg = $itemsMsg . "（已报名" . $itemSaled . ")";
//                }
//            }
            if ($itemPrice != 0) {
                $itemsMsg .= " " . $itemPrice.'元';
            }

            $itemsMsg .= "\n";

            $startNum++;
        }
        if( empty($userOrdersMsg) ){
            $itemsMsg .= $this->splitStr."💃抢沙发👇：\n";
        }
        else{
            $itemsMsg .= $this->splitStr."🍭接龙开始：\n";
            $itemsMsg .= $userOrdersMsg;
        }

        return $itemsMsg;
    }

    private function getUserOrdersInfo($activityId, $itemArrayNos)
    {
        $userOrdersMsg = '';
        //由cart统计卖出的数量
        $saledNums = array();

        //获取分享id对应的订单信息
        $order_model = loadModelObject('Order');
        $cart_model = loadModelObject('Cart');
        $user_model = loadModelObject('User');

        $orders = $order_model->find('all', array(
            'conditions' => array(
                'data_id' => $activityId,
                'model' => 'WxActivity',
                'status >=' => 1
            ),
            'fields' => array('id', 'creator'),
            'order' => 'Order.id ASC',
            'recursive' => -1,
        ));

        if (!empty($orders)) {
            foreach ($orders as $order) {
                $orderVal = $order['Order'];
                $creators[$orderVal['creator']][] = $orderVal['id'];
                $orderKeyInfo[$orderVal['id']] = $orderVal; //下单用户
            }

            $needOrderIds = array_keys($orderKeyInfo);

            //购买商品的明细信息个数之类的信息
            $carts = $cart_model->find('all', array(
                'conditions' => array(
                    'Cart.order_id' => $needOrderIds,
                ),
                'fields' => array('id', 'name', 'order_id', 'num', 'product_id', 'price'),
            ));

            //一个订单对应多条cart
            foreach ($carts as $item) {
                $order_id = $item['Cart']['order_id'];
                $baoming_id = $item['Cart']['product_id'];
                $order_cart_map[$order_id][] = $item['Cart'];
                if (!isset($saledNums[$baoming_id])) {
                    $saledNums[$baoming_id] = 0;
                }
                $saledNums[$baoming_id] += $item['Cart']['num'];
            }

            //用户纬度数据
            $countNum = 1;

            $userInfos = $user_model->find('all', array(
                'conditions' => array(
                    'User.id' => array_keys($creators)
                ),
                'fields' => array('id', 'username'),
                'recursive' => -1,
            ));

            foreach ($userInfos as $userInfo) {
                $userId = $userInfo['User']['id'];
                $userName = $userInfo['User']['username'];

                $userIdNames[$userId] = $userName;
            }


            foreach ($creators as $creKey => $cVal) {
                $userName = $userIdNames[$creKey];
                $userName = strlen($userName) > 12 ? usubstr($userName, 0, 12) . '...' : $userName;

                $userOrdersMsg .= $countNum . '.' . $userName . '：';
                foreach ($cVal as $pdOrderIdVal) {
                    $orderMapArray = $order_cart_map[$pdOrderIdVal];
                    if (count($orderMapArray) > 1) {//多个订单
                        foreach ($orderMapArray as $mapKey => $mapVal) {
                            $buyPdName = $mapVal['name'] ;
                            $buyPdName = strlen($buyPdName) > 6 ? usubstr($buyPdName, 0, 6)  : $buyPdName;
                            $userOrdersMsg .= $buyPdName. $mapVal['num'].' ' ;
                        }
                    } else {
                        $buyPdName = $order_cart_map[$pdOrderIdVal][0]['name']; //购买产品名称
                        $buyPdNum = $order_cart_map[$pdOrderIdVal][0]['num']; //购买产品数量
                        $buyPdName = strlen($buyPdName) > 6 ? usubstr($buyPdName, 0, 6)  : $buyPdName;
                        $userOrdersMsg .= $buyPdName . $buyPdNum ;
                    }
                }
                $userOrdersMsg = rtrim($userOrdersMsg) . "\n";
                $countNum++;
            }
        }

        return array($userOrdersMsg, $saledNums);
    }

    public function sendBotMessage($contactType,$contactNickName,$msg,$bot_id,$type='text'){
        $modelObj = loadModelObject('BotMessage');
        $modelObj->create();
        $modelObj->save(array(
            'receiver' => $contactNickName,
            'chat_type' => $contactType == 'friends' ? 1 : 2,
            'message' => $msg,
            'bot_id' => $bot_id,
            'type' => $type,
        ));
    }

    private function sendMessage($contactType, $contactNickName, $msg, $url,$message_type = 'text')
    {
        $this->httpPostVot($contactType, $contactNickName, $msg, $url,$message_type);
    }

    private function httpPostVot($contactType, $contactNickName, $msg, $url,$message_type = 'text')
    {
		$msg = str_replace("\r\n","\n",$msg);
        $data = array(
            'action' => "send",
            'params' => array(
                'contact-type' => $contactType,
                'nickname' => mb_convert_encoding($contactNickName, "UTF-8", "UTF-8"),
                'message-type' => $message_type,
                'content' => mb_convert_encoding($msg, "UTF-8", "UTF-8")
            )
        );
        //$this->sendMessage("friends", $username, $orderPaidMsg, $url);



        // use this code with mb_convert_encoding, you can json_encode some corrupt UTF-8 chars

//        $post_data = json_encode($data,JSON_UNESCAPED_UNICODE| JSON_UNESCAPED_SLASHES);
//
//        $curlObj = curl_init(); //初始化curl，
//        curl_setopt($curlObj, CURLOPT_URL, $url); //设置网址
//        curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); //将curl_exec的结果返回
//        curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, false);
//        curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, false);
//        curl_setopt($curlObj, CURLOPT_HEADER, 0); //是否输出返回头信息
//        curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Expect:')); // forbid 100 continue;
//        curl_setopt($curlObj, CURLOPT_POST, 1);
//        curl_setopt($curlObj, CURLOPT_POSTFIELDS, $post_data);
//        $response = curl_exec($curlObj); //执行
////        var_dump($response);
//        curl_close($curlObj); //关闭会话
//        CakeLog::debug($url . ':' . $response . "\r\ndata:".var_export($data,true)."\r\npost data:" . $post_data);
    }

    /*
     *
     * #http://cn2.php.net/manual/zh/function.json-last-error.php
    function safe_json_encode($value, $options = 0, $depth = 512) {
        $encoded = json_encode($value, $options, $depth);
        if ($encoded === false && $value && json_last_error() == JSON_ERROR_UTF8) {
            $encoded = json_encode($this->utf8ize($value), $options, $depth);
        }
        return $encoded;
    }

    function utf8ize($mixed) {
        if (is_array($mixed)) {
            foreach ($mixed as $key => $value) {
                $mixed[$key] = $this->utf8ize($value);
            }
        } elseif (is_string($mixed)) {
            return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
        }
        return $mixed;
    }*/

    function curlQuery($url)
    {
        //设置附加HTTP头
        $addHead = array(
            "Content-type: application/json"
        );
        //初始化curl，当然，你也可以用fsockopen代替
        $curl_obj = curl_init();
        //设置网址
        curl_setopt($curl_obj, CURLOPT_URL, $url);
        //附加Head内容
        curl_setopt($curl_obj, CURLOPT_HTTPHEADER, $addHead);
        //是否输出返回头信息
        curl_setopt($curl_obj, CURLOPT_HEADER, 0);
        //将curl_exec的结果返回
        curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, 1);
        //设置超时时间
        curl_setopt($curl_obj, CURLOPT_TIMEOUT, 15);
        //执行
        $result = curl_exec($curl_obj);
        //关闭curl回话
        curl_close($curl_obj);
        return $result;
    }

    //根据长网址获取短网址
    private function sinaShortenUrl($long_url)
    {
        //拼接请求地址，此地址你可以在官方的文档中查看到
        $url = 'http://api.t.sina.com.cn/short_url/shorten.json?source=' . self::$SINA_APP_KEY . '&url_long=' . urlencode($long_url);
        //获取请求结果
        $result = $this->curlQuery($url);
        //下面这行注释用于调试，
        CakeLog::debug($result);
        //解析json
        $json = json_decode($result);
        //异常情况返回false
        if ( !empty($json) && isset($json[0]->url_short) && !empty($json[0]->url_short) )
            return $json[0]->url_short;
        else
            return $long_url;
    }

    /**
     * @param $activityId
     * @return mixed
     */
    private function getRelatedData($model,$data_id)
    {
        $modelObj = loadModelObject($model);
        $data = $modelObj->find('first', array(
            'conditions' => array(
                $model.'.id' => $data_id
            ),
            'recursive' => 1,
        ));
        return $data;
    }

    /**
     * @param $orderId
     * @return mixed
     */
    private function getOrderById($orderId)
    {
        $order_model = loadModelObject('Order');
        $order = $order_model->find('first', array(
            'conditions' => array(
                'Order.id' => $orderId
            ),
            'recursive' => 1,
        ));
        return $order;
    }

    function startsWith($haystack, $needle)
    {
        $length = strlen($needle);
        return (substr($haystack, 0, $length) === $needle);
    }
}